import 'dart:convert';
import 'dart:ui';

import 'package:flutter/material.dart';
//import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:magic_car/jiance/contract.dart';
import 'package:magic_car/jiance/test_report.dart';
import 'package:magic_car/util/HttpHelper.dart';
import 'package:magic_car/util/galleryphotoview.dart';
import 'package:magic_car/zhanshi/cheyuandetail.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:toast/toast.dart';
import 'dart:io';
import 'package:date_format/date_format.dart';
import 'package:flutter/services.dart';
import 'package:magic_car/UI/bottom_Menu_page.dart';
import 'package:magic_car/UI/userbottom_Menu_page.dart';

class PapularinspectReults extends StatefulWidget {
  // final Map param;
  final String oid;
  final int type;
  PapularinspectReults(this.oid, this.type);

  @override
  _MyHomePageState createState() => new _MyHomePageState(this.oid, this.type);
}

class _MyHomePageState extends State<PapularinspectReults> {
  List formList;
  // final Map param;
  bool select = false;
  bool showUrl = false;
  final String oid;
  final int type;
  String itemid;
  List testItem;
  bool loaddata = false;
  String status;
  Map formalities;
  Map oldformalities;
  Map order_info;
  Map userinfo;
  List buchong=[];

  String pdf_url;
  _MyHomePageState(this.oid, this.type);
  TextEditingController result = new TextEditingController();
  TextEditingController resultprice = new TextEditingController();
  initState() {
    super.initState();
    formList = [
      {
        "title": '购车发票/过户票',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "value": "有",
        "code": "invoice"
      },
      {
        "title": '购置税证',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "code": "Tax",
        "value": "有"
      },
      {
        "title": '行驶证',
        'sub_title': '云A00001',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "code": "vehicle",
        "value": "有"
      },
      {
        "title": '年检有效期',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "1",
        "code": "yearcheck_e_time",
        "value": "请选择日期"
      },
      {
        "title": '登记证',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "0",
        "code": "registration",
        "value": "有"
      },
      {
        "title": '过户次数',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "2",
        "code": "transfer",
        "value": ""
      },
      {
        "title": '交强险有效期',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "1",
        "code": "compu_e_time",
        "value": "请选择日期"
      },
      {
        "title": '交强险保险公司',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "2",
        "code": "compu_name",
        "value": ""
      },
      {
        "title": '车船税有效期',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "1",
        "code": "vehicles_e_time",
        "value": "请选择日期"
      },
      // {
      //   "title": '车船险随车出售',
      //   'sub_title': '云A00001云A00001云A00',
      //   'sub_color': Color.fromRGBO(27, 182, 251, 1),
      //   'type': "3",
      //   "code": "vehicles",
      //   "value": "是"
      // },
      {
        "title": '商业险金额',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "2",
        "code": "business_price",
        "value": ""
      },
      {
        "title": '商业险保险公司',
        'sub_title': '云A00001云A00001云A00',
        'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "2",
        "code": "business_name",
        "value": ""
      },
      {
        "title": '特殊车辆',
        'sub_title': '云A00001云A00001云A00',
        // 'sub_color': Color.fromRGBO(27, 182, 251, 1),
        'type': "2",
        "code": "specialcar",
        "value": "",
        "mustimg": 0,
        'urlArr1': [],
        'urlArr': [],
        'hasimg': 0
      },
    ];
    loaduserinfo();
    loaddetail();
  }

  loaduserinfo() async {
    SharedPreferences pref = await SharedPreferences.getInstance();
    String role = pref.getString('role');
    Map<String, String> map = new Map();
    map["id"] = pref.getString('uid');

    String url = HttpHelper.API_BusinessInfo;
    if (role.toString() == '1') {
      url = HttpHelper.API_Userinfo;
    }

    HttpHelper.post(url, (data) async {
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          setState(() {
            userinfo = data["info"];
          });
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

  loaddetail() async {
    Map<String, String> map = new Map();
    map['oid'] = this.oid;
    String api = HttpHelper.API_OrderDetail;
    if (this.type == 2) {
      api = HttpHelper.API_BussinessOrderDetail;
    }
    print('000');
    HttpHelper.post(api, (data) async {
      print('111');
      if (data != null) {
        if (data["code"].toString() == "1") {
          setState(() {
            status = data["info"]["status"].toString();
            order_info = data['info'];
          });
          if (data["info"]["status"] != "0" && data["info"]["status"] != "1") {
            //print(data["info"]["inspectorItemsResult"]['result']);
            String res = '无检测结论';
            String resprice = '无评估价格';
            if (data["info"]["inspectorItemsResult"].containsKey('result')) {
              res = data["info"]["inspectorItemsResult"]['result'];
            }
            if (data["info"]["inspectorItemsResult"]
                .containsKey('result_price')) {
              resprice = data["info"]["inspectorItemsResult"]['result_price'];
            }
            setState(() {
              result.text = res;
              resultprice.text = resprice;

              testItem = data["info"]["inspectorItemsResult"]["otherData"]
                  ["checkData"];
              oldformalities =
                  data["info"]["inspectorItemsResult"]["formalities"];
              loaddata = true;
              status = data["info"]["status"].toString();
              
            });
            if(data["info"]["inspectorItemsResult"].containsKey('buchong')){
              setState(() {
                buchong = data["info"]["inspectorItemsResult"]['buchong'];
              });
            }

            Map foemlitile =
                data["info"]["inspectorItemsResult"]["formalities"];

            var templist = formList;

            for (var i = 0; i < formList.length; i++) {
              var code = formList[i]["code"];

              // if(foemlitile[code].length==0){
              //   formList[i]["value"] = "有";
              // }

              if (foemlitile[code] != "") {
                templist[i]["value"] = foemlitile[code];
              }

              if (code == "vehicles") {
                if (foemlitile[code] == true) {
                  formList[i]["value"] = "是";
                } else {
                  formList[i]["value"] = "否";
                }
              }
              if (code == "business_sell_by_car") {
                if (foemlitile[code] == true) {
                  formList[i]["value"] = "是";
                } else {
                  formList[i]["value"] = "否";
                }
              }
            }
            setState(() {
              formList = templist;
            });

            // if (data["info"]["inspectorItemsResult"] != null) {
            // if (type == 1) {
            //   setState(() {
            //     testItem = data["info"]["inspectorItemsResult"]["otherData"]
            //         ["checkData"];
            //     loaddata = true;
            //     status = data["info"]["status"].toString();
            //   });
            // }else{
            //   setState(() {

            //     loaddata = true;
            //     status = data["info"]["status"].toString();
            //   });
            // }
          } else {}

          setState(() {
            //formList = oldlist;
            // orders=data["info"];
          });
          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }

  photo(item) async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    if (image == null) return;
    //File _files = await FlutterNativeImage.compressImage(image.path);
    File _files = image;

    Map<String, String> map = new Map();

    HttpHelper.upLoadImage(_files, (data) {
      // print('data');
      if (data.containsKey('code')) {
        Toast.show(data['msg'], context);
      } else {
        List tempimg1 =
            item.containsKey("urlArr1") ? item["urlArr1"] : new List();
        List tempimg = new List();
        tempimg.add(data["filename"]);
        tempimg.add(data["url"]);
        tempimg1.add(tempimg);
        setState(() {
          item["urlArr1"] = tempimg1;
        });
      }
    }, params: map);
  }

  Widget buildcontent(item) {
    List<Widget> tiles = [];
    Widget content;
    List postdata = item["post"];
    itemid = item["id"];
    if (item["mustmodel"].toString() == "1") {
      if (itemid == "3044") {
        //浸泡检测单独处理
        String position = item['position'];
        double top_hei = 0;
        if (position == "top") {
          top_hei = 20;
        } else if (position == "center") {
          top_hei = 50;
        } else if(position=="bottom"){
          top_hei = 80;
        }
        tiles.add(Container(
            color: Colors.white,
            width: double.infinity,
            height: 200,
            padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
            //color: Colors.red,
            //color: Colors.red,
            child: Align(
              alignment: Alignment.topCenter,
              child: new Stack(
                children: <Widget>[
                  Positioned(
                      child: new Image.asset(
                    'resource/images/jiance/qinpao.png',
                  )),
                top_hei==0?Container(height: 0,):  Positioned(
                      top: top_hei,
                      left: 50,
                      right: 30,
                      height: 25,
                      child: new GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            setState(() {});
                          },
                          child: new Container(
                              height: 1,
                              decoration: BoxDecoration(
                                  border: Border(
                                      top: BorderSide(
                                width: 3,
                                color: Colors.red,
                              )))

                              //       child:
                              // new Container(
                              //   color:Colors.red,
                              //   height: line_Height1.toDouble()

                              // )
                              ))),
                ],
              ),
            )));
      } else if (itemid == "3077") {
        //灯光模型单独处理
        tiles.add(Container(
            color: Colors.white,
            width: double.infinity,
            height: 150,
            padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
            //color: Colors.red,
            //color: Colors.red,
            child: Align(
              alignment: Alignment.topCenter,
              child: showLightProblem(itemid, postdata, 1),
            )));

        tiles.add(Container(
            color: Colors.white,
            width: double.infinity,
            height: 150,
            padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
            //color: Colors.red,
            //color: Colors.red,
            child: Align(
              alignment: Alignment.topCenter,
              child: showLightBProblem(itemid, postdata, 2),
            )));
      } else {
        tiles.add(Container(
            color: Colors.white,
            width: double.infinity,
            height: 250,
            padding: new EdgeInsets.fromLTRB(0, 10, 0, 20),
            //color: Colors.red,
            //color: Colors.red,
            child: Align(
              alignment: Alignment.topCenter,
              child: showProblem(itemid, postdata),
            )));
      }
    }

    int counters = 0;

    for (var item in postdata) {
      if (item["show_report"].toString() == "1") {
        item["show_report"] = "是";
      } else if (item["show_report"].toString() == "0") {
        item["show_report"] = "否";
      }
      Color value_color = Color.fromRGBO(25, 172, 249, 1);
      if (item["item"] != null) {
        List<String> items = item["item"].split(',');

        if (item.containsKey("value") == false) {
          item["value"] = items[0];
        }
        if (item["value"] == items[0]) {
          value_color = Color.fromRGBO(25, 172, 249, 1);
        } else {
          value_color = Color.fromRGBO(203, 93, 86, 1);
          // item["value"] = '';
        }
      } else {
        value_color = Color.fromRGBO(203, 93, 86, 1);
      }

      if (item["post_id"].toString() == "3000") {
        //车辆信息
        value_color = Color.fromRGBO(25, 172, 249, 1);
      }
      TextEditingController textEditingController = TextEditingController();
      double height = 80;
      if (item["mustimg"] == "1") height = 270;

      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
          child: Container(
            color: Colors.white,
            // height: height,
            child: new Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Padding(
                    padding: new EdgeInsets.fromLTRB(15, 12, 10, 0),
                    child: new Row(
                      children: <Widget>[
                        new Text(
                          item["name"],
                          style: new TextStyle(
                              color: Color.fromRGBO(102, 102, 102, 1),
                              fontSize: 13),
                        ),
                        Expanded(
                            child: Align(
                                child: Text(
                                  item["value"] == "" ? "暂无" : item["value"],
                                  style: TextStyle(
                                      color: value_color, fontSize: 13),
                                ),
                                alignment: Alignment.centerRight)),
                      ],
                    )),
                this.type == 2 ? checkBox(item) : new Container(height: 0),
                item.containsKey("numerical_value")
                    ? testresult(item)
                    : new Text(''),
                item['id'].toString() == '9999'
                    ? rencheImg(item)
                    : item.containsKey("urlArr1")
                        ? imgs(item)
                        : Container(height: 0)
              ],
            ),
          )));
    }
    return ExpansionTile(
      children: tiles,
      title: RichText(
          text: TextSpan(
              // text: '检测项',
              text: item['name'],
              style: TextStyle(fontSize: 16.0, color: Colors.black),
              children: <TextSpan>[
            TextSpan(
                //text: "（总共：" + '项）',
                text: "（总共：" + postdata.length.toString() + '项）',
                style: TextStyle(fontSize: 12.0, color: Colors.red))
          ])),
    );
  }

  Widget rencheImg(item) {
    List<Widget> tiles = [];
    tiles.add(Padding(
      padding: new EdgeInsets.fromLTRB(10, 0, 0, 10),
      child: GestureDetector(
          onTap: () {
            List temp = [
              ['', item['url']]
            ];
            print(temp);
             Navigator.of(context).push(new FadeRoute(
                        page: GalleryPhotoViewWrapper(
                      galleryItems: imageModelinspectitem(temp),
                      backgroundDecoration: const BoxDecoration(
                        color: Colors.black,
                      ),
                      initialIndex: 1,
                    )));
            // Navigator.of(context).push(
            //   NinePicture(temp, 0),
            // );
          },
          child: Image.network(item['url'], width: 100, height: 100)),
    ));
    var content = new Row(children: tiles);
    return content;
  }
  List imageModelinspectitem(data) {
    List img_temp = [
      "https://car3.autoimg.cn/cardfs/product/g1/M09/3F/A8/240x180_0_q95_c42_autohomecar__ChwFqV69W4KAf_AzAAShphUBgV4514.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M09/6E/D2/240x180_0_q95_c42_autohomecar__ChwFj169W32Ad5ehAAT2abQFAio994.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M08/6E/D2/240x180_0_q95_c42_autohomecar__ChwFj169W3uATe71AASA9ZdptWg816.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M0B/73/06/240x180_0_q95_c42_autohomecar__ChsEmF69W3qAYeneAAQeve0abAo167.jpg",
    ];
    List imgList = List();
    for (int x = 0; x < data.length; x++) {
      
      GalleryExampleItem item = GalleryExampleItem();
      item.id = '$x';
      item.resource = data[x][1];
      // item.resource = data[x]["url"];
      imgList.add(item);
    }
    print(imgList.first.id);

    return imgList;
  }

  //漆膜仪检测的数值
  Widget testresult(item) {
    Widget content;
    List<Widget> tiles = [];
    // print(item["testnum"]);
    // int itemnum = int.parse(item["testnum"]);
    int itemnum = item['numerical_value'].length;
    for (var i = 0; i < itemnum; i++) {
      tiles.add(
        Padding(
          padding: new EdgeInsets.fromLTRB(10, 0, 0, 5),
          child: new Container(
            height: 30,
            width: 30,

            decoration: new BoxDecoration(
              border: new Border.all(color: Colors.red, width: 0.0), // 边色与边宽度
              color: Color(0xFF9E9E9E), // 底色
              //        borderRadius: new BorderRadius.circular((20.0)), // 圆角度
              borderRadius:
                  BorderRadius.all(Radius.circular(15.0)), // 也可控件一边圆角大小
            ),

            //color: Colors.red,
            child: new Align(
                alignment: Alignment.center,
                child: new Text(
                  item.containsKey('numerical_value')
                      ? item['numerical_value'][i].toString()
                      : '0',
                  style: TextStyle(color: Colors.white, fontSize: 10),
                )),
          ),
        ),
      );
    }
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    return content;
  }

  Widget imgs(item) {
    List<Widget> tiles = [];
    Widget content;

    List items = item["urlArr1"];

    for (var i = 0; i < items.length; i++) {
      List temp1 = items[i] as List;
      tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 0, 0, 10),
        child: GestureDetector(
            onTap: () {
               Navigator.of(context).push(new FadeRoute(
                        page: GalleryPhotoViewWrapper(
                      galleryItems: imageModelinspectitem(items),
                      backgroundDecoration: const BoxDecoration(
                        color: Colors.black,
                      ),
                      initialIndex: i,
                    )));
              // Navigator.of(context).push(
              //   NinePicture(items, i),
              // );
            },
            child: Image.network(temp1[1], width: 100, height: 100)),
      ));
    }
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    //content = new Row(children: tiles);

    return content;
  }

  Widget checkBox(item) {
    List<Widget> tiles = [];
    Widget content;

    List<String> items = item["item"].split(',');

    String defaultv = items[0];
    if (select == false) {
      if (item.containsKey("value") == false) {
        item['value'] = defaultv;
      }
    } //设置选项默认值
    // for (var i = 0; i < items.length; i++) {
    tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(15, 17, 0, 0),
        child: Text('是否显示在报告中：',
            style: new TextStyle(
                fontSize: 11, color: Color.fromRGBO(100, 100, 100, 1)))));
    tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
        child: SizedBox(
            width: 22,
            child: Radio<String>(
                //当前Radio的值
                hoverColor: Color.fromRGBO(200, 200, 200, 1),
                focusColor: Color.fromRGBO(25, 172, 249, 1),
                value: '是',
                activeColor: Color.fromRGBO(25, 172, 249, 1),
                groupValue: item['show_report'],
                // groupValue: defaultv,
                onChanged: (value) {
                  setState(() {
                    select = true;
                    // defaultv = value;
                    item['show_report'] = value;
                  });
                }))));

    tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 17, 0, 0),
        child: Text('是',
            style: new TextStyle(
                fontSize: 11, color: Color.fromRGBO(100, 100, 100, 1)))));
    tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 0, 0, 0),
        child: SizedBox(
            width: 22,
            child: Radio<String>(
                //当前Radio的值
                hoverColor: Color.fromRGBO(200, 200, 200, 1),
                focusColor: Color.fromRGBO(25, 172, 249, 1),
                value: '否',
                activeColor: Color.fromRGBO(25, 172, 249, 1),
                groupValue: item['show_report'],
                // groupValue: defaultv,
                onChanged: (value) {
                  setState(() {
                    select = true;
                    // defaultv = value;
                    item['show_report'] = value;
                  });
                }))));

    tiles.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 17, 0, 0),
        child: Text('否',
            style: new TextStyle(
                fontSize: 11, color: Color.fromRGBO(100, 100, 100, 1)))));
    //}
    content = new Wrap(spacing: 0, runSpacing: 0, children: tiles);
    //content = new Row(children: tiles);

    return content;
  }

  backhome() {
    if (type == 1) {
      final PageRouteBuilder _homeRoute = new PageRouteBuilder(
        pageBuilder: (BuildContext context, _, __) {
          return UBotomeMenumPage();
        },
      );
      Navigator.pushAndRemoveUntil(
          context, _homeRoute, (Route<dynamic> r) => false);
    } else {
      // return new BotomeMenumPage();
      final PageRouteBuilder _homeRoute = new PageRouteBuilder(
        pageBuilder: (BuildContext context, _, __) {
          return BotomeMenumPage();
        },
      );
      Navigator.pushAndRemoveUntil(
          context, _homeRoute, (Route<dynamic> r) => false);
    }
  }

  Widget build(BuildContext context) {
    return Scaffold(
      //key: _scaffoldKey,
      appBar: AppBar(
        title: Text('检测结果'),
        backgroundColor: Colors.white,
        elevation: 0,
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.endFloat,
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          backhome();
        },
        child: Icon(
          Icons.home,
          color: Colors.white,
        ),
        backgroundColor: Color.fromRGBO(27, 182, 251, 1),
      ),
      body: Container(
        height: 800,
        color: Colors.white,
        child: Stack(children: <Widget>[
          Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 0, 10),
              child: loaddata
                  ? ListView(
                      children: _buildList(),
                    )
                  : new Text('')),
          // Align(
          //     alignment: Alignment.bottomCenter,
          //     child: Padding(
          //       padding: new EdgeInsets.fromLTRB(0, 0, 0, 0),
          //       child: Container(
          //         width: double.infinity,
          //         color: Color.fromRGBO(27, 182, 251, 1),
          //         child: new FlatButton(
          //             onPressed: () {
          //               // connect();
          //              // subOrder(0);
          //             },
          //             child: new Text(
          //               '检测完成？提交',
          //               style: TextStyle(color: Colors.white),
          //             )),
          //       ),
          //     )),
        ]),
      ),
    );
  }

  Widget buildBtn() {
    List<Widget> widgets = [];
    Widget content;
    if (status == '2' || status == "3") {
      widgets.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 10, 0, 30),
          child: new Container(
              color: Colors.white,
              //color:Colors.white,
              child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                  child: new Material(
                    color: Colors.white,
                    //INK可以实现装饰容器
                    child: new Ink(
                      //用ink圆角矩形
                      //color: Color.fromRGBO(239, 239, 239, 1),
                      decoration: new BoxDecoration(
                        //背景

                        color: Color.fromRGBO(27, 182, 251, 1),
                        //设置四周圆角 角度
                        borderRadius: BorderRadius.all(Radius.circular(18.0)),
                        //设置四周边框
                        border: new Border.all(
                            width: 1, color: Color.fromRGBO(27, 182, 251, 1)),
                      ),
                      child: new InkWell(

                          //圆角设置,给水波纹也设置同样的圆角
                          //如果这里不设置就会出现矩形的水波纹效果
                          borderRadius: new BorderRadius.circular(15.0),
                          //设置点击事件回调
                          onTap: () async {
                            // reportdown();
                            SharedPreferences pref =
                                await SharedPreferences.getInstance();
                            String role = pref.getString('role');

                            String url = HttpHelper.host +
                                '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.b_test_reports&id=' +
                                this.oid +
                                '&ismobile=1';
                            if (order_info["bussiness_id"].toString() != "0") {
                              // 如果是认证检测的订单
                              url = HttpHelper.host +
                                  '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.test_reports&id=' +
                                  this.oid;

                              print(url);
                              Navigator.of(context)
                                  .push(new MaterialPageRoute(builder: (_) {
                                return new WebPage(url, this.oid,"1");
                              }));
                            } else {
                              if (role.toString() == '1') {
                                if (order_info['test_type'] == "保修检测") {
                                  if (order_info['contract'] == null) {
                                    Toast.show('暂不能查看', context);
                                    return;
                                  }

                                  String url = HttpHelper.host +
                                      '/app/index.php?i=16&c=entry&m=chemogu&do=mobile&r=car.contract&id=' +
                                      this.oid;
                                  Navigator.of(context)
                                      .push(new MaterialPageRoute(builder: (_) {
                                    return new ContractPage(url, this.oid);
                                  }));
                                } else {
                                  //用户的报告连接
                                  if (order_info['test_type'] == "金融检测") {
                                    //assement
                                    url = HttpHelper.host +
                                        '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.assement&id=' +
                                        this.oid;
                                  } else
                                    url = HttpHelper.host +
                                        '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.test_reports&id=' +
                                        this.oid;

                                  print(url);
                                  Navigator.of(context)
                                      .push(new MaterialPageRoute(builder: (_) {
                                    return new WebPage(url, this.oid,"0");
                                  }));
                                }
                              }
                            }
                          },
                          child: Container(
                            //设置 child 居中
                            alignment: Alignment(0, 0),
                            height: 36,
                            //color: Color.fromRGBO(239, 239, 239, 1),
                            width: double.infinity,
                            child: Text(
                              order_info['test_type'] == "保修检测"
                                  ? '查看合同'
                                  : "打印报告",
                              style: TextStyle(color: Colors.white),
                            ),
                          )),
                    ),
                  )))));
    }
    if (type == 2 && status == "3") {
      widgets.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 0, 30),
          child: new Container(
              color: Colors.white,
              //color:Colors.white,
              child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                  child: new Material(
                    color: Colors.white,
                    //INK可以实现装饰容器
                    child: new Ink(
                      //用ink圆角矩形
                      //color: Color.fromRGBO(239, 239, 239, 1),
                      decoration: new BoxDecoration(
                        //背景

                        color: Color.fromRGBO(27, 182, 251, 1),
                        //设置四周圆角 角度
                        borderRadius: BorderRadius.all(Radius.circular(18.0)),
                        //设置四周边框
                        border: new Border.all(
                            width: 1, color: Color.fromRGBO(27, 182, 251, 1)),
                      ),
                      child: new InkWell(

                          //圆角设置,给水波纹也设置同样的圆角
                          //如果这里不设置就会出现矩形的水波纹效果
                          borderRadius: new BorderRadius.circular(15.0),
                          //设置点击事件回调
                          onTap: () {
                            subOrder(1);
                            // reportdown();
                            // String url = HttpHelper.host +
                            //     '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.b_test_reports&id=' +
                            //     this.oid;
                            // print(url);
                            // Navigator.of(context)
                            //     .push(new MaterialPageRoute(builder: (_) {
                            //   return new WebPage(url);
                            // }));
                          },
                          child: Container(
                            //设置 child 居中
                            alignment: Alignment(0, 0),
                            height: 36,
                            //color: Color.fromRGBO(239, 239, 239, 1),
                            width: double.infinity,
                            child: Text(
                              "生成报告",
                              style: TextStyle(color: Colors.white),
                            ),
                          )),
                    ),
                  )))));

      widgets.add(Padding(
        padding: new EdgeInsets.fromLTRB(10, 0, 10, 0),
        child: new Center(
            child: Text('注*：当更改过检测结果时，请先点击生成报告，否则更改无效',
                style: (TextStyle(color: Colors.red, fontSize: 12)))),
      ));
    }

    if (showUrl) {
      widgets.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 10, 0, 0),
          child: new Container(
              color: Colors.white,
              //color:Colors.white,
              child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                  child: Align(
                      alignment: Alignment.center,
                      child: new Text('报告已生成，点击下方链接，在电脑端查看和打印'))))));
      widgets.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 10, 0, 0),
          child: new Container(
              color: Colors.white,
              //color:Colors.white,
              child: new Padding(
                  padding: new EdgeInsets.fromLTRB(10, 0, 20, 0),
                  child: Align(
                      alignment: Alignment.center,
                      child: FlatButton(
                          onPressed: () {
                            Clipboard.setData(ClipboardData(text: pdf_url));
                            Toast.show('链接已复制', context);
                          },
                          child: new Text(pdf_url)))))));
    } else {
      widgets.add(new Text(''));
    }
    content = new Column(
      children: widgets,
    );
    return content;
  }

//下载报告
  reportdown() {
    if (order_info['is_pay_report'] == '1') {
      //已经支付过
      setState(() {
        showUrl = true;
        pdf_url = HttpHelper.host +
            '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.test_pdf&id=' +
            this.oid +
            '&token=' +
            order_info['report_token'];
      });
    } else {
      //
      var user_balance = double.parse(userinfo['balance']);
      var report_fee = double.parse(order_info['report_fee']);
      if (user_balance < report_fee) {
        //充值

      } else {
        //

        //  setState(() {
        //    showUrl=true;
        //    pdf_url = HttpHelper.host+'/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.test_pdf&id='+this.oid+'&token='+order_info['report_token'];
        //  });

        update_order();
      }
    }
  }

  update_order() async {
    //更新订单信息
    SharedPreferences pref = await SharedPreferences.getInstance();
    String role = pref.getString('role');
    Map<String, String> map = new Map();
    map["bid"] = pref.getString('uid');

    map["oid"] = this.oid;

    String url = HttpHelper.API_UptBussinessOrder;

    HttpHelper.post(url, (data) async {
      if (data != null) {
        print(data);
        //Toast.show(data["msg"], context);

        if (data["code"].toString() == "1") {
          setState(() {
            showUrl = true;
            pdf_url = HttpHelper.host +
                '/app/index.php?i=16&j=16&c=entry&m=chemogu&do=mobile&r=car.test_pdf&id=' +
                this.oid +
                '&token=' +
                data['info']['token'];
          });

          //pref.setStringList('userinfo', data["info"]);

        }
      }
    }, params: map);
  }
   List imageModel(data) {
    List img_temp = [
      "https://car3.autoimg.cn/cardfs/product/g1/M09/3F/A8/240x180_0_q95_c42_autohomecar__ChwFqV69W4KAf_AzAAShphUBgV4514.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M09/6E/D2/240x180_0_q95_c42_autohomecar__ChwFj169W32Ad5ehAAT2abQFAio994.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M08/6E/D2/240x180_0_q95_c42_autohomecar__ChwFj169W3uATe71AASA9ZdptWg816.jpg",
      "https://car2.autoimg.cn/cardfs/product/g25/M0B/73/06/240x180_0_q95_c42_autohomecar__ChsEmF69W3qAYeneAAQeve0abAo167.jpg",
    ];
    List imgList = List();
    for (int x = 0; x < data.length; x++) {
      GalleryExampleItem item = GalleryExampleItem();
      item.id = '$x';
      item.resource = data[x]['img'];
      // item.resource = data[x]["url"];
      imgList.add(item);
    }
    print(imgList.first.id);

    return imgList;
  }

  Widget buchongcontent(){
    List<Widget>tiles=[];
    tiles.add(Container(
        
        child:Text("补充图片说明",style:TextStyle(fontSize:16))
      ));
    for(int i =0;i<buchong.length;i++){
     tiles.add(
       Container(
         margin: EdgeInsets.only(top:10),
         child:Row(
           crossAxisAlignment:CrossAxisAlignment.start,
           children: [
             InkWell(
               onTap:(){
                  Navigator.of(context).push(new FadeRoute(
                page: GalleryPhotoViewWrapper(
              galleryItems: imageModel(buchong),
              backgroundDecoration: const BoxDecoration(
                color: Colors.black,
              ),
              initialIndex: i,
            )));
               },
               child:
             Container(
               margin:EdgeInsets.only(right:10),
               child:
             CachedNetworkImage(imageUrl: buchong[i]['img'],width:130,height:100,fit:BoxFit.fitWidth))),

             Expanded(child: 
             Text("说明：${buchong[i]['remark']}",style:TextStyle(fontSize:13))),
            // InkWell(
            //   onTap:(){
            //     buchong.removeAt(i);
            //     setState(() {
            //       buchong = buchong;
            //     });
            //   },
            //   child: SizedBox(
            //    child:Image.asset("resource/images/user/delets.png",width:25,height:25)
            //  ))

           ],
         )
       )
     );
    }
   
    return Container(
      padding:new EdgeInsets.fromLTRB(15, 10, 10, 10),
      child:Column(
        crossAxisAlignment:CrossAxisAlignment.start,
        children:tiles
      )
    );
  }


  List<Widget> _buildList() {
    List<Widget> widgets = [];
    widgets.add(buildcontents());
    //print(testItem.length);
    for (var item in testItem) {
      widgets.add(buildcontent(item));
    }

    widgets.add(buchongcontent());

    widgets.add(new Container(
        child: new Padding(
      padding: new EdgeInsets.fromLTRB(10, 10, 10, 10),
      child: TextField(
        enabled: false,
        enableInteractiveSelection: false,
        onTap: () {
          FocusScope.of(context).requestFocus(new FocusNode());
        },
        maxLines: 5,
        controller: result,
        decoration: InputDecoration(
            border: InputBorder.none,
            fillColor: Color.fromRGBO(238, 238, 238, 1),
            filled: true,
            labelStyle: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),
            labelText: '最终检测结论'),
      ),
    )));
    if (order_info['test_type'] == '金融检测') {
      widgets.add(new Container(
          child: new Padding(
        padding: new EdgeInsets.fromLTRB(10, 10, 10, 10),
        child: TextField(
          enabled: false,
          enableInteractiveSelection: false,
          onTap: () {
            FocusScope.of(context).requestFocus(new FocusNode());
          },
          maxLines: 1,
          controller: resultprice,
          decoration: InputDecoration(
              border: InputBorder.none,
              fillColor: Color.fromRGBO(238, 238, 238, 1),
              filled: true,
              labelStyle: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),
              labelText: '最终评估价格（万）'),
        ),
      )));
    }

    widgets.add(buildBtn());
    //  widgets.add(buildcontents());

    return widgets;
  }

  //手续信息单独处理
  Widget itemContent(item) {
    var child;
    if (item["type"] == "0") {
      child = Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
          child: Row(
            // crossAxisAlignment: CrossAxisAlignment.end,
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              Radio<String>(
                  //当前Radio的值
                  hoverColor: Color.fromRGBO(200, 200, 200, 1),
                  focusColor: Color.fromRGBO(25, 172, 249, 1),
                  value: "有",
                  activeColor: Color.fromRGBO(25, 172, 249, 1),
                  groupValue: item["value"],
                  // groupValue: defaultv,
                  onChanged: (value) {
                    String code = item["code"];
                    // String code = item["code"];

                    setState(() {
                      item["value"] = value;
                      formalities[code] = value;
                      // paytype = value;
                    });
                  }),
              new Text("有",
                  style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1))),
              Radio<String>(
                  //当前Radio的值
                  hoverColor: Color.fromRGBO(200, 200, 200, 1),
                  focusColor: Color.fromRGBO(25, 172, 249, 1),
                  value: "无",
                  activeColor: Color.fromRGBO(25, 172, 249, 1),
                  groupValue: item["value"],
                  // groupValue: defaultv,
                  onChanged: (value) {
                    // String code = item["code"];
                    String code = item["code"];
                    // item["value"] = value;
                    // formalities[code] = value;
                    setState(() {
                      item["value"] = value;
                      formalities[code] = value;
                    });
                  }),
              new Text("无",
                  style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1))),
            ],
          ));
    } else if (item["type"] == "1") {
      DateTime initialDate = DateTime.now();
      child = Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
          child: Align(
              alignment: Alignment.centerRight,
              child: new GestureDetector(
                  child: new Text(item["value"]),
                  onTap: () async {
                    final DateTime dateTime = await showDatePicker(
                      context: context,
                      //定义控件打开时默认选择日期
                      initialDate: initialDate,
                      //定义控件最早可以选择的日期
                      firstDate: DateTime(2018, 1),
                      //定义控件最晚可以选择的日期
                      lastDate: DateTime(2050, 1),
                      //locale: Locale.fromSubtags(languageCode: 'zh'),
                      // builder: (BuildContext context, Widget child) {
                      //   return Theme(
                      //     data: CommonColors.themData,
                      //     child: child,
                      //   );
                      // },
                    );
                    // Locale myLocale = Localizations.localeOf(context);
                    // final DateTime picker = await showDatePicker(
                    //     context: context,
                    //     initialDate: DateTime.now(),
                    //     firstDate: DateTime(2016),
                    //     lastDate: DateTime(2019),
                    //     locale: myLocale);
                    // setState(() {
                    //   item["value"] = picker.toString();
                    // });
                    if (dateTime != null) {
                      setState(() {
                        String code = item["code"];
                        item["value"] =
                            formatDate(dateTime, [yyyy, "-", mm, "-", dd]);
                        formalities[code] = item["value"];
                      });
                    }
                  })));
    } else if (item["type"] == "2") {
      child = new TextField(
          onChanged: (value) {
            String code = item["code"];
            item["value"] = value;
            formalities[code] = value;
          },
          textAlign: TextAlign.right,
          //controller: _validtroller,
          decoration: InputDecoration(
              hintText: item["value"] == "" ? '请填写信息' : item["value"],
              border: OutlineInputBorder(
                borderSide: BorderSide.none,
              )));
    } else if (item["type"] == "3") {
      child = Switch(
        //当前状态
        value: item["value"] == "是" ? true : false,
        // 激活时原点颜色
        activeColor: Colors.blue,
        inactiveTrackColor: Colors.blue.shade50,
        onChanged: (value) {
          //重新构建页面
          setState(() {
            String code = item["code"];
            item["value"] = value == true ? "是" : "否";
            formalities[code] = value;
          });
        },
      );
    }

    if (item["type"] == "3") {
      return new Padding(
          padding: new EdgeInsets.fromLTRB(0, 0, 10, 0), child: child);
    } else {
      return Expanded(
          child: new Padding(
              padding: new EdgeInsets.fromLTRB(0, 0, 10, 0), child: child));
    }
  }

  Widget buildcontents() {
    List<Widget> tiles = [];
    Widget content;
    int counters = 0;
    for (var item in formList) {
      if (item.containsKey('value')) {
        if (item["value"] != "") {
          counters++;
        }
      }
      tiles.add(Padding(
          padding: new EdgeInsets.fromLTRB(0, 1, 0, 0),
          child: Container(
              color: Colors.white,
              height: 50,
              child: new Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  Expanded(
                      child: new Padding(
                          padding: new EdgeInsets.fromLTRB(15, 0, 10, 0),
                          child: Align(
                              alignment: Alignment.centerLeft,
                              child: new Text(
                                item['title'],
                                style: TextStyle(
                                    fontSize: 15,
                                    color: Color.fromRGBO(102, 102, 102, 1)),
                              )))),
                  status == "0" || status == "1"
                      ? itemContent(item)
                      : Expanded(
                          child: Padding(
                              padding: new EdgeInsets.fromLTRB(0, 0, 15, 0),
                              child: Align(
                                  alignment: Alignment.centerRight,
                                  child: new Text(item["value"]))))
                  // Expanded(
                  //   child: new Padding(
                  //       padding: new EdgeInsets.fromLTRB(0, 0, 10, 0),
                  //       child: new TextField(
                  //           textAlign: TextAlign.right,
                  //           //controller: _validtroller,
                  //           decoration: InputDecoration(
                  //             hintText: '验证码',
                  //             border: OutlineInputBorder(
                  //               borderSide: BorderSide.none,
                  //             ),
                  //           ))),
                  // child: new Text(
                  //   item['sub_title'],
                  //   style:
                  //       TextStyle(fontSize: 15, color: item['sub_color']),
                  // )),
                  //)
                ],
              ))));
    }
    return ExpansionTile(
      children: tiles,
      title: RichText(
          text: TextSpan(
              text: '手续信息',
              style: TextStyle(fontSize: 16.0, color: Colors.black),
              children: <TextSpan>[
            TextSpan(
                text: "（总共：" + formList.length.toString() + '项）',
                style: TextStyle(fontSize: 12.0, color: Colors.red))
          ])),
      // title: Text(
      //   item["name"],
      //   style: TextStyle(
      //     color: Colors.black,
      //     fontSize: 16,
      //   ),
      // )
    );
    // content = new Column(
    //     children: tiles //重点在这里，因为用编辑器写Column生成的children后面会跟一个<Widget>[]，
    //     //此时如果我们直接把生成的tiles放在<Widget>[]中是会报一个类型不匹配的错误，把<Widget>[]删了就可以了
    //     );
    // return content;
  }

//灯光异常图片
  Widget showLightBProblem(itemid, postdata, type) {
    // List postData = param["post"];
    String modelUrl = "resource/images/jiance/model/light/light_b.png";

    List<Widget> tiles = [];
    Widget content;
    //每次都要加载这张图片，后续优化
    // if (type == 1) {
    tiles.add(
      Positioned(
          child: new Image.asset(
        modelUrl,
        //fit:BoxFit.none
        //fit: BoxFit.fi,
      )),
    );
    for (var i = 0; i < postdata.length; i++) {
      var item = postdata[i];
      var id = item["id"];
      List<String> items = item["item"].split(',');
      String urls = '';
      for (int n = 0; n < items.length; n++) {
        if (item["value"] == items[n]) {
          if (n == 0) continue;
          if (int.parse(id) < 4010 && int.parse(id) != 4014) continue;
          //urls = 'resource/images/jiance/model/boli/40202.png';
          urls = 'resource/images/jiance/model/light/' +
              id.toString() +
              '-' +
              n.toString() +
              '.png';
          try {
            tiles.add(
              Positioned(child: new Image.asset(urls)),
            );
          } catch (e) {
            print(e);
          }
        }
      }
    }

    content = new Stack(children: tiles);
    return content;
  }

  //灯光异常图片
  Widget showLightProblem(itemid, postdata, type) {
    // List postData = param["post"];
    String modelUrl = "resource/images/jiance/model/light/light_f.png";

    List<Widget> tiles = [];
    Widget content;
    //每次都要加载这张图片，后续优化
    // if (type == 1) {
    tiles.add(
      Positioned(
          child: new Image.asset(
        modelUrl,
        //fit:BoxFit.none
        //fit: BoxFit.fi,
      )),
    );
    for (var i = 0; i < postdata.length; i++) {
      var item = postdata[i];
      var id = item["id"];
      List<String> items = item["item"].split(',');

      String urls = '';
      for (int n = 0; n < items.length; n++) {
        if (item["value"] == items[n]) {
          if (n == 0) continue;

          if (int.parse(id) > 4009 && int.parse(id) != 4014) continue;
          //urls = 'resource/images/jiance/model/boli/40202.png';
          urls = 'resource/images/jiance/model/light/' +
              id.toString() +
              '-' +
              n.toString() +
              '.png';
          try {
            tiles.add(
              Positioned(child: new Image.asset(urls)),
            );
          } catch (e) {
            print(e);
          }
        }
      }
    }

    content = new Stack(children: tiles);
    return content;
  }

  //异常图片
  Widget showProblem(itemid, postdata) {
    List<Widget> tiles = [];
    Widget content;
    List postData = postdata;
    String modelUrl = "resource/images/jiance/carmodel2.png";
    if (itemid == "3043") {
      //结构件
      modelUrl = "resource/images/jiance/model/jiegou/jiegou.jpg";
    } else if (itemid == "3076") {
      //车身玻璃
      modelUrl = "resource/images/jiance/model/boli/boli.png";
    } else if (itemid == "3044") {
      //浸泡检测
      modelUrl = "resource/images/jiance/qinpao.png";
    }
    try {
      tiles.add(
        Positioned(
            child: new Image.asset(
          modelUrl,
          //fit:BoxFit.none
          //fit: BoxFit.fi,
        )),
      );
    } catch (e) {
      print(e);
    }

    if (itemid != "3044") {
      // List postData = param["post"];
      for (var item in postData) {
        List<String> items = item["item"].split(',');

        var id = item["id"];
        // print(id);
        if (item.containsKey("value")) {
          if (item["post_id"] == "3076") {
            String urls;
            for (int n = 0; n < items.length; n++) {
              if (item["value"] == items[n]) {
                if (n == 0) continue;
                //urls = 'resource/images/jiance/model/boli/40202.png';
                urls = 'resource/images/jiance/model/boli/' +
                    id.toString() +
                    '-' +
                    n.toString() +
                    '.png';
              }
            }
            if (item["value"] != items[0]) {
              // File imgs = File(urls);
              // var dir_bool = imgs.exists();
              // print(dir_bool);
              // print(urls);
              try {
                tiles.add(
                  Positioned(child: new Image.asset(urls)),
                );
              } catch (e) {
                print(e);
              }
            }
          } else {
            if (items[0] != item["value"]) {
              String urls;
              if (item["post_id"] == "3043") {
                urls = 'resource/images/jiance/model/jiegou/' +
                    id.toString() +
                    '.png';
              } else {
                for (int n = 0; n < items.length; n++) {
                  if (item["value"] == items[n]) {
                    if (n == 0) continue;
                    int tempv = 1;
                    if (n == 1) {
                      tempv = 2;
                    }
                    urls = 'resource/images/jiance/model/qimian/' +
                        id.toString() +
                        '-' +
                        tempv.toString() +
                        '.png';
                    //urls = 'resource/images/jiance/model/boli/40202.png';
                    // urls = 'resource/images/jiance/model/boli/' +
                    //     id.toString() +
                    //     '-' +
                    //     n.toString() +
                    //     '.png';
                  }
                }
              }
              // File imgs = File(urls);
              // var dir_bool = imgs.exists();
              try {
                tiles.add(
                  Positioned(
                      //     child: new Image.asset(
                      //   'resource/images/jiance/xlgx.png'
                      //   //fit:BoxFit.none
                      //   //fit: BoxFit.fi,
                      // )
                      child: new Image.asset(urls
                          //fit:BoxFit.none
                          //fit: BoxFit.fi,
                          )),
                );
              } catch (e) {
                print(e);
              }
            }
          }
        }
      }
    }
    content = new Stack(children: tiles);
    return content;
  }

  //提交检测项
  subOrder(types) {
    print(this.status);
    // if (this.orderStatus == "0"||this.orderStatus == "1") {
    Map<String, Object> map = new Map();
    map["oid"] = this.oid;
    map["type"] = this.type.toString();
    if (types == 1) {
      for (var item in testItem) {
        for (var items in item["post"]) {
          if (items["show_report"] == "是") {
            items["show_report"] = "1";
          }
          if (items["show_report"] == "否") {
            items["show_report"] = "0";
          }
        }
      }
    }
    Map chechdata1 = {"checkData": testItem};

    Map checkdata = {"otherData": chechdata1, "formalities": formalities};
    if (types == 1) {
      //生成报告单时，手续信息不变
      checkdata = {"otherData": chechdata1, "formalities": oldformalities};
    }
    // checkdata["otherData"]["checkData"]=testItem;
    // map["inspector"] = jsonEncode(testItem);
    map["inspector"] = jsonEncode(checkdata);
    // print('传递的检测项');
    // print(map);
    HttpHelper.post(HttpHelper.API_SubOrder, (data) async {
      if (data != null) {
        Toast.show(data["msg"], context);
        // print('上传检测项');
        // print(data);
        if (data["code"].toString() == "1") {
          if (types == 1) {
            // setState(() {
            //   showUrl = true;
            // });
          } else {
            Navigator.pop(context);
          }
        }
      }
    }, params: map);
    // }
  }

  Future<bool> willpop() {
    // _showDialog();
    Navigator.pop(context);
    return Future.value(false);
  }

  _showDialog() {
    showDialog<Null>(
      context: this.context,
      builder: (BuildContext context) {
        return new AlertDialog(
            title: Text('提示!'),
            content: new Text('此项是否已经检测完毕?'),
            actions: <Widget>[
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    // Navigator.pop(context);
                  },
                  child: new Text('否，继续检测',
                      style: new TextStyle(color: Colors.red))),
              new FlatButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    Navigator.pop(context);
                  },
                  child: new Text(
                    '是',
                    style: new TextStyle(color: Colors.black),
                  ))
            ]);
      },
    );
  }
}

class NinePicture<T> extends PopupRoute<T> {
  final String barrierLabel;
  final List picList;
  final int index;
  int startX;
  int endX;

  NinePicture(this.picList, this.index, {this.barrierLabel});

  @override
  Duration get transitionDuration => Duration(milliseconds: 2000);

  @override
  @override
  Color get barrierColor => Colors.black54;

  @override
  bool get barrierDismissible => true;

  AnimationController _animationController;

  @override
  AnimationController createAnimationController() {
    assert(_animationController == null);
    _animationController =
        BottomSheet.createAnimationController(navigator.overlay);
    return _animationController;
  }

  @override
  Widget buildPage(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation) {
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: GestureDetector(
        child: AnimatedBuilder(
          animation: animation,
          builder: (BuildContext context, Widget child) => GestureDetector(
            onTap: () {
              Navigator.pop(context);
            },
            child: _PictureWidget(picList, index),
          ),
        ),
      ),
    );
  }
}

class _PictureWidget extends StatefulWidget {
  final List picList;
  final int index;

  _PictureWidget(this.picList, this.index);

  @override
  State createState() {
    return _PictureWidgetState();
  }
}

class _PictureWidgetState extends State<_PictureWidget> {
  int startX = 0;
  int endX = 0;
  int index = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    index = widget.index;
  }

  @override
  Widget build(BuildContext context) {
    return new Material(
      color: Colors.transparent,
      child: new Container(
        width: double.infinity,
        child: Stack(
          children: <Widget>[
            GestureDetector(
              child: Center(
                child: CachedNetworkImage(
                  imageUrl: widget.picList[index][1],
                  fit: BoxFit.cover,
                ),
              ),
              onHorizontalDragDown: (detail) {
                startX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragUpdate: (detail) {
                endX = detail.globalPosition.dx.toInt();
              },
              onHorizontalDragEnd: (detail) {
                _getIndex(endX - startX);
                setState(() {});
              },
              onHorizontalDragCancel: () {},
            ),
            Align(
              alignment: Alignment.bottomCenter,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: List.generate(
                  widget.picList.length,
                  (i) => GestureDetector(
                    child: CircleAvatar(
                      foregroundColor: Theme.of(context).primaryColor,
                      radius: 8.0,
                      backgroundColor: index == i
                          ? Theme.of(context).primaryColor
                          : Colors.white,
                    ),
                    onTap: () {
                      setState(() {
                        startX = endX = 0;
                        index = i;
                      });
                    },
                  ),
                ).toList(),
              ),
            )
          ],
        ),
        alignment: Alignment.center,
      ),
    );
  }

  void _getIndex(int delta) {
    if (delta > 50) {
      setState(() {
        index--;
        index = index.clamp(0, widget.picList.length - 1);
      });
    } else if (delta < 50) {
      setState(() {
        index++;
        index = index.clamp(0, widget.picList.length - 1);
      });
    }
  }
}
